#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import json
import sys
import argparse
import subprocess
from urllib.request import urlopen, Request
from urllib.error import URLError, HTTPError
import shutil

# 配置文件路径
USER_DATA_FILE = "users.json"
REPO_DATA_FILE = "repositories.json"
REMOTE_JSON_URL = "https://atomgit.com/wujianson/cinux/master/"

def ensure_json_files():
    """确保JSON文件存在，如果不存在则创建空文件"""
    for file_path in [USER_DATA_FILE, REPO_DATA_FILE]:
        if not os.path.exists(file_path):
            print(f"创建缺失的文件: {file_path}")
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump([], f, ensure_ascii=False, indent=2)

def download_json_files():
    """从远程仓库下载JSON文件"""
    print("正在从远程仓库下��JSON文件...")
    
    files_to_download = {
        "users.json": USER_DATA_FILE,
        "repositories.json": REPO_DATA_FILE
    }
    
    success_count = 0
    for remote_name, local_path in files_to_download.items():
        try:
            url = REMOTE_JSON_URL + remote_name
            req = Request(url)
            
            # 添加User-Agent头以避免被某些服务器拒绝
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
            
            with urlopen(req) as response:
                data = response.read().decode('utf-8')
                json_data = json.loads(data)
                
                # 备份旧文件
                if os.path.exists(local_path):
                    backup_path = local_path + ".bak"
                    shutil.copy2(local_path, backup_path)
                    print(f"已备份旧文件: {backup_path}")
                
                # 写入新文件
                with open(local_path, 'w', encoding='utf-8') as f:
                    json.dump(json_data, f, ensure_ascii=False, indent=2)
                
                print(f"成功下载: {local_path}")
                success_count += 1
                
        except HTTPError as e:
            print(f"下载 {remote_name} 时出错: HTTP错误 {e.code}")
        except URLError as e:
            print(f"下载 {remote_name} 时出错: {e.reason}")
        except Exception as e:
            print(f"下载 {remote_name} 时出错: {str(e)}")
    
    return success_count

def load_json_data(file_path):
    """加载JSON数据"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"加载 {file_path} 时出错: {str(e)}")
        return []

def save_json_data(file_path, data):
    """保存JSON数据"""
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存 {file_path} 时出错: {str(e)}")
        return False

def register_user(username, password, user_id):
    """注册新用户"""
    users = load_json_data(USER_DATA_FILE)
    
    # 检查用户名是否已存在
    if any(user['username'] == username for user in users):
        print(f"错误: 用户名 '{username}' 已存在")
        return False
    
    # 检查用户ID是否已存在
    if any(user['userId'] == user_id for user in users):
        print(f"错误: 用户ID '{user_id}' 已存在")
        return False
    
    # 添加新用户
    new_user = {
        "username": username,
        "password": password,
        "userId": user_id
    }
    
    users.append(new_user)
    
    if save_json_data(USER_DATA_FILE, users):
        print(f"成功注册用户: {username} (ID: {user_id})")
        return True
    else:
        print("注册用户失败")
        return False

def add_repository(user_id, repo_name, repo_desc, repo_url):
    """为用户添加仓库"""
    repos = load_json_data(REPO_DATA_FILE)
    
    # 检查用户是否存在
    users = load_json_data(USER_DATA_FILE)
    if not any(user['userId'] == user_id for user in users):
        print(f"错误: 用户ID '{user_id}' 不存在")
        return False
    
    # 检查URL是否已存在
    if any(repo['url'] == repo_url for repo in repos):
        print(f"错误: 仓库URL '{repo_url}' 已存在")
        return False
    
    # 添加新仓库
    new_repo = {
        "id": len(repos) + 1,
        "name": repo_name,
        "description": repo_desc,
        "url": repo_url,
        "userId": user_id
    }
    
    repos.append(new_repo)
    
    if save_json_data(REPO_DATA_FILE, repos):
        print(f"成功为用户 {user_id} 添加仓库: {repo_name}")
        return True
    else:
        print("添加仓库失败")
        return False

def list_users():
    """列出所有用户"""
    users = load_json_data(USER_DATA_FILE)
    
    if not users:
        print("没有用户数据")
        return
    
    print("\n用户列表:")
    print("-" * 50)
    for i, user in enumerate(users, 1):
        print(f"{i}. {user['username']} (ID: {user['userId']})")

def list_repositories(user_id=None):
    """列出仓库，可选的按用户ID过滤"""
    repos = load_json_data(REPO_DATA_FILE)
    users = load_json_data(USER_DATA_FILE)
    
    if not repos:
        print("没有仓库数据")
        return
    
    # 创建用户ID到用户名的映射
    user_map = {user['userId']: user['username'] for user in users}
    
    filtered_repos = repos
    if user_id:
        filtered_repos = [repo for repo in repos if repo['userId'] == user_id]
        if not filtered_repos:
            print(f"用户ID '{user_id}' 没有仓库")
            return
    
    print("\n仓库列表:")
    print("-" * 80)
    for repo in filtered_repos:
        owner_name = user_map.get(repo['userId'], '未知用户')
        print(f"名称: {repo['name']}")
        print(f"描述: {repo.get('description', '无描述')}")
        print(f"URL: {repo['url']}")
        print(f"所有者: {owner_name} (ID: {repo['userId']})")
        print("-" * 80)

def upload_changes(commit_message):
    """使用git上传更改"""
    try:
        # 添加所有更改
        subprocess.run(["git", "add", USER_DATA_FILE, REPO_DATA_FILE], check=True)
        
        # 提交更改
        subprocess.run(["git", "commit", "-m", commit_message], check=True)
        
        # 推送到远程仓库
        result = subprocess.run(["git", "push"], capture_output=True, text=True)
        
        if result.returncode == 0:
            print("成功上传更改到远程仓库")
            return True
        else:
            print("上传更改失败:")
            print(result.stderr)
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"Git操作失败: {str(e)}")
        return False
    except FileNotFoundError:
        print("错误: 未找到git命令，请确保已安装Git并配置好环境变量")
        return False

def main():
    """主函数"""
    # 确保JSON文件存在
    ensure_json_files()
    
    # 设置命令行参数解析
    parser = argparse.ArgumentParser(description="Cinux 数据管理工具")
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # update命令：从远程更新JSON文件
    update_parser = subparsers.add_parser('update', help='从远程仓库更新JSON文件')
    
    # register命令：注册新用户
    register_parser = subparsers.add_parser('register', help='注册新用户')
    register_parser.add_argument('username', help='用户名')
    register_parser.add_argument('password', help='密码')
    register_parser.add_argument('userid', help='用户ID')
    
    # add-repo命令：添加仓库
    add_repo_parser = subparsers.add_parser('add-repo', help='为用户添加仓库')
    add_repo_parser.add_argument('userid', help='用户ID')
    add_repo_parser.add_argument('name', help='仓库名称')
    add_repo_parser.add_argument('desc', help='仓库描述')
    add_repo_parser.add_argument('url', help='仓库URL')
    
    # list-users命令：列出所有用户
    subparsers.add_parser('list-users', help='列出所有用户')
    
    # list-repos命令：列出仓库
    list_repos_parser = subparsers.add_parser('list-repos', help='列出仓库')
    list_repos_parser.add_argument('--userid', help='按用户ID过滤')
    
    # upload命令：上传更改到远程仓库
    upload_parser = subparsers.add_parser('upload', help='上传更改到远程仓库')
    upload_parser.add_argument('-m', '--message', required=True, help='提交消息')
    
    # 如果没有提供参数，显示帮助信息
    if len(sys.argv) == 1:
        parser.print_help()
        return
    
    # 解析参数
    args = parser.parse_args()
    
    # 执行相应命令
    if args.command == 'update':
        success_count = download_json_files()
        print(f"更新完成，成功下载 {success_count}/2 个文件")
        
    elif args.command == 'register':
        register_user(args.username, args.password, args.userid)
        
    elif args.command == 'add-repo':
        add_repository(args.userid, args.name, args.desc, args.url)
        
    elif args.command == 'list-users':
        list_users()
        
    elif args.command == 'list-repos':
        list_repositories(args.userid)
        
    elif args.command == 'upload':
        upload_changes(args.message)
        
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
